//前端开发环境
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var sio = require('socket.io');
var fs = require('fs');
var amqp = require('amqplib');
var when = require('when');
var app = express();

//所有中间件和功能
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser({uploadDir:__dirname+'/uploads'}));
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

//开发专用
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

routes(app);

var server = http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

var socket = sio.listen(server);
socket.on('connection',function(socket){
    console.log('io成功建立链接');
});

app.all('/PUSH', function(req, res){
          res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive'
          });
          res.write('\n');
          setInterval(function(){
            res.write("id: " + Date.now()  + "\n");
            res.write("data: " + '服务器推送 ' + "\n\n");
          }, 5000);
        });


app.post('/post', function(req, res){
    res.send('123');
});

app.post('/model', function(req, res){
    res.send('123');
});

amqp.connect('amqp://127.0.0.1').then(function(conn){
    process.once('SIGINT',function(){conn.close()});
    return conn.createChannel().then(function(ch){
        var ok = ch.assertQueue('hello',{durable: false});
        //队列监听
        ok = ok.then(function(_qok){
            return ch.consume('hello',function(msg){
                console.log(msg.content.toString());
            },{noAck: true})
        });
        return ok.then(function(_consumeOK){
            console.log('waiting');
        });
    });
}).then(null, console.warn);

//hello world
amqp.connect('amqp://localhost').then(function(conn){
    return when(conn.createChannel().then(function(ch){
        var q = 'hello';
        var msg = 'Hello World';
        var ok = ch.assertQueue(q,{durable: false});

        return ok.then(function(_qok){
            ch.sendToQueue(q,new Buffer(msg));
            console.log(msg);
            return ch.close();
        }).ensure(function(){conn.close();});
    }))
}).then(null,console.warn);